﻿using System;
using System.Web;
using Lync.Widget.Library.Presence;
using log4net;

namespace Lync.Widget.Library.Web
{
    public class Global : System.Web.HttpApplication
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Global));

        public Global()
        {
             BeginRequest += OnBeginRequest;
        }
        
        private void Application_End(object sender, EventArgs e)
        {
            StopPresenceQueryService();
        }

        private void StopPresenceQueryService()
        {
            UcmaHelper.GetInstance().Stop();
            Log.Info("LyncWidget service stopped successfully");
        }

        public void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            Log.Error("Unhandled exception {0}", ex);
            Server.ClearError();
        }
        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
        
        
      
       
        private void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }
    }
}